<template>
  <div class="login-container">
    <div class="welcome-content">
      <!-- 左侧展示的欢迎内容 -->
      <h1>Welcome to Doctor Go</h1>
      <h2>Find the best healthcare professionals</h2>
    </div>
    <div class="login-form">
      <!-- 右侧登录框 -->
      <h2>登录</h2>
      <el-form @submit.prevent="login">
        <el-form-item label="Username" required>
          <el-input v-model="username"></el-input>
        </el-form-item>
        <el-form-item label="Password" required>
          <el-input type="password" v-model="password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" native-type="submit">Login</el-button>
        </el-form-item>
      </el-form>
      <div class="register-link">
        <span>还没有账户?</span>
        <el-button @click="showRegisterBox" type="text">点我注册</el-button>
      </div>
      <el-button @click="showUnRegisterBox" type="text">注销账号</el-button>
    </div>
    <div class="rightpad">
      <h1></h1>
    </div>

    <el-dialog
      v-model="showUnRegister"
      title="Unregister"
      @close="closeUnRegisterBox"
    >
      <el-form :model="unregisterForm" :rules="unregisterRules" ref="unregisterForm" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="unregisterForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="unregisterForm.password"></el-input>
        </el-form-item>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeUnRegisterBox">取消</el-button>
          <el-button type="primary" @click="submitUnForm('unregisterForm')">注销</el-button>
        </div>
      </el-form>
    </el-dialog>

    <el-dialog
      v-model="showRegister"
      title="Register"
      @close="closeRegisterBox"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email"></el-input>
          <el-button @click="sendVerificationCode">发送验证码</el-button>
          <el-input v-model="inputCode" placeholder="请输入验证码" />
          <el-button @click="verifyCode">验证验证码</el-button>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input type="password" v-model="form.confirmPassword"></el-input>
        </el-form-item>
        <el-form-item label="用户类型" prop="userType">
          <el-radio-group v-model="form.userType">
            <el-radio label="2">Doctor</el-radio>
            <el-radio label="1">Patient</el-radio>
          </el-radio-group>
        </el-form-item>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeRegisterBox">取消</el-button>
          <el-button type="primary" @click="submitForm('form')">注册</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
  <div class="bottompad"></div>
</template>

<script>
import { ElButton, ElInput, ElDialog, ElForm, ElFormItem, ElMessage, ElRadio, ElRadioGroup, ElMessageBox } from 'element-plus';
import axios from 'axios';
import router from '@/router';
import { mapMutations } from 'vuex';

export default {
  components: {
    ElButton,
    ElInput,
    ElDialog,
    ElForm,
    ElFormItem,
    ElRadio,
    ElRadioGroup
  },
  data() {
    const validateUsername = (rule, value, callback) => {
      const usernamePattern = /^[a-zA-Z][a-zA-Z0-9_]*$/;
      if (!value) {
        return callback(new Error('用户名不能为空'));
      }
      if (!usernamePattern.test(value)) {
        return callback(new Error('用户名必须以字母开头，并且只能包含字母、数字和下划线'));
      }
      callback();
    };

    const validatePhone = (rule, value, callback) => {
      const phonePattern = /^[0-9]{11}$/;
      if (!value) {
        return callback(new Error('手机号不能为空'));
      }
      if (!phonePattern.test(value)) {
        return callback(new Error('手机号必须是11位数字'));
      }
      callback();
    };

    const validateEmail = (rule, value, callback) => {
      const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      if (!value) {
        return callback(new Error('邮箱不能为空'));
      }
      if (!emailPattern.test(value)) {
        return callback(new Error('邮箱格式不正确'));
      }
      callback();
    };

    return {
      userType: '',
      username: 'patient',
      password: '123456',
      confirmPassword: '',
      showRegister: false,
      showUnRegister: false,
      inputCode: '',
      verificationData: null,
      isVerified: false,
      form: {
        username: '',
        phone: '',
        email: '',
        password: '',
        confirmPassword: '',
        userType: ''
      },
      unUserId: '',
      unregisterForm: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, validator: validateUsername, trigger: 'blur' }
        ],
        phone: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ],
        email: [
          { required: true, validator: validateEmail, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: (rule, value, callback) => {
            if (value !== this.form.password) {
              callback(new Error('两次输入的密码不一致'));
            } else {
              callback();
            }
          }, trigger: 'blur' }
        ],
        userType: [
          { required: true, message: '请选择用户类型', trigger: 'change' }
        ]
      },
      unregisterRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    ...mapMutations(['SET_ROLE']),
    login() {
      console.log('Login:', this.username, this.password);
      axios.post('http://localhost:8085/api/user/login', {
        userName: this.username,
        userPassword: this.password
      })
      .then(response => {
        const { code, msg, data } = response.data;
        switch (code) {
          case 0:
            ElMessage.error(msg);
            break;
          case 1:
            ElMessage.success('登录成功！');
            console.log(data);
            let userType = '';
            if (data.userType == 1) {
              userType = "patient";
            } else if (data.userType == 2) {
              userType = "doctor";
            } else if (data.userType == 3) {
              userType = "admin";
            }
            this.SET_ROLE({ curUserType: userType, curId: data.userId, curUsername: data.userName });
            this.$nextTick(() => {
              console.log("当前状态: " + this.$store.state.userName);
            });
            router.push('/' + userType);
            break;
          default:
            ElMessage.warning('未知的响应码');
            break;
        }
      })
      .catch(error => {
        ElMessage.error('请求失败，请稍后重试');
        console.error('Login error:', error);
      });
    },
    showRegisterBox() {
      this.showRegister = true;
    },
    closeRegisterBox() {
      this.showRegister = false;
    },
    showUnRegisterBox() {
      this.showUnRegister = true;
    },
    closeUnRegisterBox() {
      this.showUnRegister = false;
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.register();
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },
    submitUnForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.unregister();
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },
    sendVerificationCode() {
      axios.get('http://localhost:8085/api/user/verifyCode', {
        params: {
          targetEmailBox: this.form.email
        }
      })
      .then(response => {
        const { code, msg, data } = response.data;
        if (code === 1) {
          ElMessage.success('验证码已发送到邮箱，请查收');
          this.verificationData = data;
        } else {
          ElMessage.error(msg);
        }
      })
      .catch(error => {
        ElMessage.error('发送验证码失败，请稍后重试');
        console.error('发送验证码错误:', error);
      });
    },
    verifyCode() {
      axios.post(`http://localhost:8085/api/user/verifyCode/${this.inputCode}`, {
        tamp: this.verificationData.tamp,
        hash: this.verificationData.hash
      })
      .then(response => {
        const { code, msg, data } = response.data;
        if (code === 1) {
          ElMessage.success('验证码验证成功');
          this.isVerified = true;
        } else {
          ElMessage.error(msg);
        }
      })
      .catch(error => {
        ElMessage.error('验证码验证失败，请稍后重试');
        console.error('验证码验证错误:', error);
      });
    },
    register() {
      if (!this.isVerified) {
        ElMessage.error('请先验证邮箱验证码');
        return;
      }
      console.log('Register:', this.form.username, this.form.phone, this.form.email);
      const data = {
        userName  : this.form.username,
        userPassword: this.form.password,
        email: this.form.email,
        userPhone: this.form.phone,
        userType: this.form.userType,
      };
      axios.post('http://localhost:8085/api/user/register', data)
      .then(response => {
        const { code, msg, data } = response.data;
        switch (code) {
          case 0:
            ElMessage.error(msg);
            break;
          case 1:
            ElMessage.success('注册成功！');
            this.showRegister = false;
            break;
        }
      })
      .catch(error => {
        ElMessage.error('注册失败');
      });
    },
    unregister() {
      axios.get('http://localhost:8085/api/user/username/'+this.unregisterForm.username).then(response =>{
        if(response.data.code === 1){
          this.unUserId = response.data.data.userId 
        }
      }),

      axios.delete('http://localhost:8085/api/user/unregister', {
        data: {
          userId: this.unUserId,
          userPassword: this.unregisterForm.password
        }
      })
      .then(response => {
        const { code, msg } = response.data;
        switch (code) {
          case 0:
            ElMessage.error(msg);
            break;
          case 1:
            ElMessage.success('账号已注销！');
            this.showUnRegister = false;
            router.push('/');
            break;
        }
      })
      .catch(error => {
        ElMessage.error('注销账号失败');
      });
    }
  }
};
</script>

<style>
.login-container {
  display: flex;
  justify-content: space-between;
  background-color: #f2f2f2;
}

.welcome-content {
  flex: 2;
  padding: 40px;
}

.login-form {
  margin-top: 20%;
  flex: 0.5;
  padding: 40px;
  background-color: #ffffff;
}

.register-link {
  margin-top: 20px;
}

.rightpad {
  flex: 0.5;
}

.bottompad {
  background: #f2f2f2;
  height: 800px;
}

.el-dialog__wrapper {
  width: 400px;
}
</style>
